package com.xuerhua.yxt.excel;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.View;

/**
 * 用于基于模板的Excel导出
 */
public class ExcelTemplateView implements View {
    /**
     * View的名字
     */
    public static final String VIEW_NAME = "excelTemplateView";

    public static final String MODEL_NAME = "EXCEL_MODEL";

    public static final String FILE_NAME = "FILE_NAME";

    /**
     * 实际返回到客户端的流
     */
    public static final String INPUT_STREAM = ExcelTemplateView.class.getName() + ".INPUT_STREAM";

    public String getContentType() {
        return MimeTypeUtils.getMimeType("xls");
    }

    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName=(String)model.get(FILE_NAME);
        if(StringUtils.isBlank(fileName)){
            fileName="data.xls";
        }
        response.setContentType(getContentType());
        response.addHeader("Content-Disposition", "contentDisposition = attachment;filename*=utf8''" + URLEncoder.encode(fileName, "utf-8"));
                
        // response.setContentLength((Integer) model.get(CONTENT_LENGTH));

        OutputStream os = null;
        InputStream is = (InputStream)model.get(INPUT_STREAM);
        os = response.getOutputStream();
        ExcelUtils.export(is, model.get(MODEL_NAME), os);

    }

}
